# -*- coding: utf-8 -*-
"""
Created on Wed Jan  6 19:28:48 2021

@author: lv-wei
"""

import turtle
import winsound

PADDLE_DY = 5

wn = turtle.Screen()
wn.title("Pong by @JasonLv")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

# Score
score_a = 0
score_b = 0

# Paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")  # 20 * 20
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)  # 100 * 20
paddle_a.penup()
paddle_a.goto(-350, 0)

# Paddle b
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)

# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.1
ball.dy = -0.1

# Pen
pen = turtle.Turtle()
pen.goto(0, 240)
pen.color("white")
pen.speed(0)
pen.penup()
pen.hideturtle()
pen.write("Player A: 0  Player B: 0",
          align="center", font=("Courier", 24, "normal"))


# Function


def paddle_a_up():
    paddle_a.sety(paddle_a.ycor() + PADDLE_DY)


def paddle_a_down():
    paddle_a.sety(paddle_a.ycor() - PADDLE_DY)


def paddle_b_up():
    paddle_b.sety(paddle_b.ycor() + PADDLE_DY)


def paddle_b_down():
    paddle_b.sety(paddle_b.ycor() - PADDLE_DY)


wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")


while True:
    wn.update()
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)

    if (ball.ycor() > 280):
        ball.dy *= -1
        # os.system("")
        winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)

    if (ball.ycor() < -280):
        ball.dy *= -1
        winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)

    if (ball.xcor() > 340 and ball.xcor() < 350) \
        and (ball.ycor() < paddle_b.ycor() + 50 and
             ball.ycor() > paddle_b.ycor() - 50):
        ball.dx *= -1
        ball.setx(340)
        winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)

    if (ball.xcor() < -340 and ball.xcor() > -350) \
        and (ball.ycor() < paddle_a.ycor() + 50 and
             ball.ycor() > paddle_a.ycor() - 50):
        ball.dx *= -1
        ball.setx(-340)
        winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)

    if (ball.xcor() > 350):
        ball.goto(0, 0)
        ball.dx *= -1
        score_a += 1
        pen.clear()
        pen.write("Player A: {}  Player B: {}".format(score_a, score_b),
                  align="center", font=("Courier", 24, "normal"))
        winsound.PlaySound("failed.wav", winsound.SND_ASYNC)

    if (ball.xcor() < -350):
        ball.goto(0, 0)
        ball.dx *= -1
        score_b += 1
        pen.clear()
        pen.write("Player A: {}  Player B: {}".format(score_a, score_b),
                  align="center", font=("Courier", 24, "normal"))
        winsound.PlaySound("failed.wav", winsound.SND_ASYNC)
